import os
import subprocess
import sys

import requests

"""
JS API
"""


class API:
    def download_file(self, fileUrl):
        # 获取文件名
        local_filename = fileUrl.split('/')[-1] + ".md"
        # 发送 GET 请求下载文件
        with requests.get(fileUrl, stream=True) as response:
            response.raise_for_status()
            # 将文件保存到本地
            with open(local_filename, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    file.write(chunk)

        # 打开文件所在目录
        file_dir = os.path.dirname(os.path.abspath(local_filename))
        if os.name == 'nt':  # Windows
            os.startfile(file_dir)
        elif os.name == 'posix':  # macOS/Linux
            subprocess.run(['open' if sys.platform == 'darwin' else 'xdg-open', file_dir])

    def download_files(self, fileUrl):
        # 获取文件名、
        print(fileUrl)
        local_filename = fileUrl.split('/')[-1] + ".zip"
        # 发送 GET 请求下载文件
        with requests.get(fileUrl, stream=True) as response:
            response.raise_for_status()
            # 将文件保存到本地
            with open(local_filename, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    file.write(chunk)

        # 打开文件所在目录
        file_dir = os.path.dirname(os.path.abspath(local_filename))
        if os.name == 'nt':  # Windows
            os.startfile(file_dir)
        elif os.name == 'posix':  # macOS/Linux
            subprocess.run(['open' if sys.platform == 'darwin' else 'xdg-open', file_dir])
